package com.ruoyi.oss.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.oss.dao.SysOssDownloadRecordsDao;
import com.ruoyi.oss.domain.SysOss;
import com.ruoyi.oss.domain.SysOssDownloadRecords;
import com.ruoyi.oss.domain.bo.SysOssDownloadRecordsSearchBo;
import com.ruoyi.oss.domain.vo.SysOssDownloadRecordsVo;
import com.ruoyi.oss.mapper.SysOssDownloadRecordsMapper;
import com.ruoyi.oss.service.SysOssDownloadRecordsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Slf4j
@Service
public class SysOssDownloadRecordsServiceImpl extends ServiceImpl<SysOssDownloadRecordsMapper, SysOssDownloadRecords> implements SysOssDownloadRecordsService {

    private SysOssDownloadRecordsDao sysOssDownloadRecordsDao;

    @Autowired
    public void setSysOssDownloadRecordsDao(SysOssDownloadRecordsDao sysOssDownloadRecordsDao) {
        this.sysOssDownloadRecordsDao = sysOssDownloadRecordsDao;
    }

    /**
     * 记录下载记录
     *
     * @param userId             用户
     * @param sysOss             文件信息
     * @param httpServletRequest 请求信息
     * @return 保存后的记录
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public SysOssDownloadRecords recordDownload(Long userId, SysOss sysOss, HttpServletRequest httpServletRequest) {
        SysOssDownloadRecords ossDownloadRecords = new SysOssDownloadRecords();
        ossDownloadRecords.setDownloadTime(new Date());
        ossDownloadRecords.setSysOssId(sysOss.getId());
        ossDownloadRecords.setUserId(userId);
        String ipAddr = IpUtils.getIpAddr(httpServletRequest);
        ossDownloadRecords.setIpAddress(ipAddr);
        String userAgent = httpServletRequest.getHeader("User-Agent");
        ossDownloadRecords.setUserAgent(userAgent);
        return sysOssDownloadRecordsDao.save(ossDownloadRecords);
    }

    /**
     * 列表查询
     *
     * @param searchBo   搜索参数
     * @param pageDomain 分页参数
     * @return 分页数据
     */
    @Override
    public Page<SysOssDownloadRecordsVo> pageList(SysOssDownloadRecordsSearchBo searchBo, PageDomain pageDomain) {
        Page<SysOssDownloadRecordsVo> page = PageUtils.buildPagePlus(pageDomain);
        return baseMapper.pageList(searchBo, page);
    }
}

